package main

import (
	"flag"
	"fmt"
	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
	"io"
	"net/http"
	"os"
	"path/filepath"
)

const (
	// 4M
	UPLOAD_FILE_MAX_SIZE = 10 * 1024 * 1024
)

var (
	port *string
	path *string
)

func init() {
	port = flag.String("port", ":1531", "server port")
	path = flag.String("path", "dist", "dir path")
}

func upload(c echo.Context) error {
	name := c.FormValue("name")
	password := c.FormValue("password")
	if name != "pedro" || password != "123456" {
		return echo.NewHTTPError(300, "密码或名称错误")
	}
	form, err := c.MultipartForm()
	if err != nil {
		return err
	}
	files := form.File["fileFolder"]

	for _, file := range files {
		// 48887 48k   2 * 1024 * 1024 2M
		if file.Size > UPLOAD_FILE_MAX_SIZE {
			return echo.NewHTTPError(400, "上传文件，每个必须小于10M")
		}
		if file.Filename == "index.html" {
			return echo.NewHTTPError(400, "上传文件中不能在根路径中带有index.html")
		}
		src, err := file.Open()
		if err != nil {
			return echo.NewHTTPError(400, err.Error())
		}
		defer src.Close()
		trueFileName := fmt.Sprintf("%s", file.Filename)
		dir, _ := filepath.Split(trueFileName)
		err = os.MkdirAll(dir, os.ModeDir)
		if err != nil {
			return echo.NewHTTPError(400, err.Error())
		}
		dst, err := os.OpenFile(trueFileName, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
		if err != nil {
			return echo.NewHTTPError(400, err.Error())
		}
		defer dst.Close()

		if _, err = io.Copy(dst, src); err != nil {
			return echo.NewHTTPError(400, err.Error())
		}
	}
	return c.JSON(http.StatusOK, map[string]string{
		"msg": "上传成功",
	})
}

func main() {
	// parse
	flag.Parse()

	e := echo.New()

	e.Use(middleware.Logger())
	e.Use(middleware.Recover())
	e.Use(middleware.Gzip())

	e.Static("/", *path)
	e.Static("/dev", "public")
	e.POST("/upload", upload)
	e.Logger.Fatal(e.Start(*port))
}
